<template>
  <div class="card">
    <h2 class="text-lg font-bold">累计新增就业人数</h2>
    <div class="chart-container bg-white rounded-lg shadow p-2 pb-5">
      <LineChart
        :data="newEmploymentData"
        :options="newEmploymentDataOptions"
        class="w-full h-48"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 初始数据（直接定义，不使用响应式）
const INITIAL_HISTORICAL_DATA = [16, 16.5, 14, 15.5]
const INITIAL_YEARS = ['2021年', '2022年', '2023年', '2024年']

// 预测函数 - 使用线性回归进行预测
const predictData = (data) => {
  if (!data || data.length < 2) return 0 // 确保有足够的数据点

  const n = data.length
  let sumX = 0
  let sumY = 0
  let sumXY = 0
  let sumX2 = 0

  data.forEach((value, index) => {
    sumX += index + 1
    sumY += value
    sumXY += (index + 1) * value
    sumX2 += (index + 1) * (index + 1)
  })

  const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX)
  const intercept = (sumY - slope * sumX) / n

  return slope * (n + 1) + intercept
}

// 计算完整数据集（包括预测值）
const fullData = computed(() => {
  const prediction = predictData(INITIAL_HISTORICAL_DATA)
  return [...INITIAL_HISTORICAL_DATA, prediction]
})

// 计算完整标签
const fullLabels = computed(() => [...INITIAL_YEARS, '2025年(预测)'])

// 计算 borderDash 数组
const borderDashArray = computed(() =>
  fullData.value.map((_, index) => (index < INITIAL_HISTORICAL_DATA.length ? 0 : 5)),
)

// 图表数据
const newEmploymentData = computed(() => ({
  labels: fullLabels.value,
  datasets: [
    {
      label: '新增就业(万人)',
      data: fullData.value,
      borderColor: '#FFC107',
      backgroundColor: 'rgba(255, 193, 7, 0.1)',
      fill: true,
      borderDash: borderDashArray.value,
      pointBackgroundColor: (context) =>
        context.dataIndex === INITIAL_HISTORICAL_DATA.length ? 'rgba(255, 99, 132, 1)' : '#FFC107',
    },
  ],
}))

// 图表配置
const newEmploymentDataOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    mode: 'index',
    intersect: false,
  },
  scales: {
    x: {
      grid: {
        display: false,
      },
      ticks: {
        color: '#666',
        maxRotation: 0,
      },
    },
    y: {
      beginAtZero: true,
      grid: {
        color: 'rgba(0, 0, 0, 0.05)',
      },
      ticks: {
        color: '#666',
        callback: (value) => value + '万人',
      },
    },
  },
  plugins: {
    legend: {
      labels: {
        color: '#333',
      },
    },
    tooltip: {
      mode: 'index',
      intersect: false,
      callbacks: {
        label: (context) => {
          let label = context.dataset.label || ''
          if (label) label += ': '
          if (context.parsed.y !== null) {
            label += context.parsed.y + '万人'
            if (context.dataIndex === INITIAL_HISTORICAL_DATA.length) {
              label += ' (预测)'
            }
          }
          return label
        },
      },
    },
  },
}))
</script>

<style scoped>
.chart-container {
  height: 200px;
}
</style>
